import {Component, inject} from '@angular/core';
import {CommonModule} from '@angular/common';
import {HousingLocationComponent} from '../housing-location/housing-location.component';
import {HousingService} from '../housing.service';
import {HousingLocation} from "../housinglocation";

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [CommonModule,
    HousingLocationComponent],
  template: `
    <section>
      <form>
        <input type="text" placeholder="城市名称" #filter>
        <button class="primary" type="button" (click)="filterResults(filter.value)">搜索</button>
      </form>
    </section>
    <section class="results">
      <app-housing-location
        *ngFor="let housingLocation of filteredLocationList"
        [housingLocation]="housingLocation">
      </app-housing-location>
    </section>
  `,
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
  housingLocationList: HousingLocation[] = [];
  //引入服务层对象
  housingService: HousingService = inject(HousingService);
  filteredLocationList: HousingLocation[] = [];

  constructor() {
    //构造方法执行页面初始化时的页面数据请求
    this.housingLocationList = this.housingService.getAllHousingLocations();
    this.filteredLocationList = this.housingLocationList;
  }

  filterResults(value: string) {
    if (!value) {
      //没有内容，默认显示全部
      this.filteredLocationList = this.housingLocationList;
    } else {
      //执行过滤
      this.filteredLocationList = this.housingLocationList.filter(
        housingLocation => housingLocation?.name.includes(value)
      );
    }
  }
}
